package com.icaikee.common.container;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

    public static final String SHUTDOWN_HOOK_KEY = "container.shutdown.hook";

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    private static volatile boolean running = true;

    static Container container;

    public static void main(String[] args) {
        try {
            container = new SpringContainer();
            if ("true".equals(System.getProperty(SHUTDOWN_HOOK_KEY))) {
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    public void run() {
                        try {
                            container.stop();
                            logger.info(container.getClass().getSimpleName() + " stopped!");
                        } catch (Throwable t) {
                            logger.error(t.getMessage(), t);
                        }
                        synchronized (Main.class) {
                            running = false;
                            Main.class.notify();
                        }
                    }
                });
            }
            container.start();
            logger.info(container.getClass().getSimpleName() + " started!");
            System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " server started!");
        } catch (RuntimeException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.exit(1);
        }
        synchronized (Main.class) {
            while (running) {
                try {
                    Main.class.wait();
                } catch (Throwable e) {
                }
            }
        }
    }

}